package com.boc.langxiang.ui.fragment.common;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.common.LoginContract;
import com.boc.langxiang.contract.common.OtherLoginContract;
import com.boc.langxiang.entity.events.LoginSuccessEvent;
import com.boc.langxiang.presenter.common.LoginPresenter;
import com.boc.langxiang.presenter.common.OtherLoginPresenter;
import com.boc.langxiang.ui.activity.common.BindPhoneActivity;
import com.boc.langxiang.ui.activity.common.ForgetPassword1Activity;
import com.boc.langxiang.ui.fragment.BaseFragment;
import com.boc.langxiang.util.KeyBoardUtil;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.tencent.connect.common.Constants;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登陆
 */
public class LoginFragment extends BaseFragment implements LoginContract.View, Handler.Callback {

    @BindView(R.id.phone)
    EditText mPhone;
    @BindView(R.id.forget)
    TextView mForget;
    @BindView(R.id.password)
    EditText mPassword;
    @BindView(R.id.login)
    TextView mLogin;
    @BindView(R.id.qq)
    ImageView mQq;
    @BindView(R.id.sina)
    ImageView mSina;
    @BindView(R.id.weixin)
    ImageView mWeixin;
    private LoginContract.Presenter mPresenter;

    private UMShareAPI mShareAPI;
    private String mOauthType;
    private String mOauthId;
    private boolean mIsAuthorSuccess;
    private SHARE_MEDIA mCurrentPlatform;
    private Map<String, String> mCurrentData;
    private Handler mHandler;
    private OtherLoginContract.Presenter mOtherLoginPresenter;

    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter = new LoginPresenter(this);
        mShareAPI = UMShareAPI.get(mContext);
        mHandler = new Handler(this);
        mOtherLoginPresenter = new OtherLoginPresenter(new OtherLoginContract.View() {
            @Override
            public void onLoginSuccess() {
                LoginFragment.this.loginSuccess();
            }

            @Override
            public void showLoading() {
                LoginFragment.this.showLoading();
            }

            @Override
            public void hideLoading() {
                LoginFragment.this.hideDialog();
            }

            @Override
            public void onError(String code, String msg) {
                if (code.equals("0022")) {
                    T.showShort(mContext, "该账号还没有绑定手机，请进行绑定操作");
                    Intent intent = new Intent(mContext, BindPhoneActivity.class);
                    intent.putExtra("lx", mOauthType);
                    intent.putExtra("openid", mOauthId);
                    mContext.startActivity(intent);
                } else {
                    T.showShort(mContext, msg);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.forget, R.id.login, R.id.qq, R.id.sina, R.id.weixin})
    public void onClick(View view) {
        SHARE_MEDIA platform = null;
        switch (view.getId()) {
            case R.id.forget:
                startActivity(new Intent(mContext, ForgetPassword1Activity.class));
                break;
            case R.id.login:
                String phone = mPhone.getText().toString();
                if (StringUtil.isEmpty(phone)) {
                    T.showShort(mContext, "请输入手机号");
                    return;
                }
                String password = mPassword.getText().toString();
                if (StringUtil.isEmpty(password)) {
                    T.showShort(mContext, "请输入密码");
                    return;
                }
                KeyBoardUtil.closeKeybord(getActivity());
                mPresenter.login(phone, password);
                break;
            case R.id.sina:
                platform = SHARE_MEDIA.SINA;
                doOauthVerify(platform);
                break;
            case R.id.weixin:
                platform = SHARE_MEDIA.WEIXIN;
                doOauthVerify(platform);
                break;
            case R.id.qq:
                platform = SHARE_MEDIA.QQ;
                doOauthVerify(platform);
                break;
        }
    }

    private void doOauthVerify(SHARE_MEDIA platform) {
        mShareAPI.doOauthVerify(getActivity(), platform, umAuthListener);
    }

    /**
     * auth callback interface
     **/
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(mContext, "第三登录授权成功!", Toast.LENGTH_SHORT).show();
            mIsAuthorSuccess = true;
            mCurrentPlatform = platform;
            mCurrentData = data;

            mHandler.sendEmptyMessageDelayed(100, 1500);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(mContext, "第三登录授权失败!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(mContext, "授权取消", Toast.LENGTH_SHORT).show();
        }
    };

    public void onActivityResult1(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void showLoading() {
        showProgressDialog("正在登录...");
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, msg);
    }

    @Override
    public void loginSuccess() {
        T.showShort(mContext, "登录成功");
//        startActivity(new Intent(mContext, MainActivity.class));
        EventBus.getDefault().post(new LoginSuccessEvent());
    }

    @Override
    public boolean handleMessage(Message msg) {
        int what = msg.what;
        switch (what) {
            case 100:
                if (mIsAuthorSuccess) {
                    mIsAuthorSuccess = false;
                    if (mCurrentPlatform == SHARE_MEDIA.SINA) {
                        //uid
                        mOauthType = LoginPresenter.SINA;
                        mOauthId = mCurrentData.get("uid");
//                        mAuthToken = mCurrentData.get(Constants.PARAM_ACCESS_TOKEN);
                        mOtherLoginPresenter.authLogin(LoginPresenter.SINA, mCurrentData.get("uid"));
                    } else if (mCurrentPlatform == SHARE_MEDIA.WEIXIN) {
                        //openid
                        mOauthType = LoginPresenter.WEIXIN;
                        mOauthId = mCurrentData.get(Constants.PARAM_OPEN_ID);
//                        mAuthToken = mCurrentData.get(Constants.PARAM_ACCESS_TOKEN);
                        mOtherLoginPresenter.authLogin(LoginPresenter.WEIXIN, mCurrentData.get("openid"));
                    } else if (mCurrentPlatform == SHARE_MEDIA.QQ) {
                        //openid
                        mOauthType = LoginPresenter.QQ;
                        mOauthId = mCurrentData.get(Constants.PARAM_OPEN_ID);
//                        mAuthToken = mCurrentData.get(Constants.PARAM_ACCESS_TOKEN);
                        mOtherLoginPresenter.authLogin(LoginPresenter.QQ, mCurrentData.get("openid"));
                    }
                }

                break;
        }
        return false;
    }
}